/**
 * 
 */
package ru.opedge.notifical.bot.xmpp;

import java.util.logging.Logger;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

import ru.opedge.notifical.notification.Notification;
import ru.opedge.notifical.notification.service.INotificationService;
import ru.opedge.notifical.notification.service.ServiceException;

/**
 * @author opedge
 * 
 */
public class NotificationBotMessageListner implements MessageListener
{
	private final INotificationService service;

	private final int delay;

	private static Logger logger = Logger.getLogger("ru.opedge.notifical");

	public NotificationBotMessageListner(final INotificationService service,
			final int delay)
	{
		this.service = service;
		this.delay = delay;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.jivesoftware.smack.MessageListener#processMessage(org.jivesoftware
	 * .smack.Chat, org.jivesoftware.smack.packet.Message)
	 */
	@Override
	public void processMessage(final Chat chat, final Message msg)
	{
		Message botMessage = null;
		try
		{
			logger.info("Received message: " + msg.getBody() + " from "
					+ msg.getFrom());
			logger.info("Trying to send notification...");

			botMessage = new Message();
			try
			{
				final String from = msg.getFrom().split("/")[0];
				service.saveNotification(new Notification(msg.getBody() + " "
						+ from, delay));
				botMessage.setBody("Message successfully sent.");
			}
			catch (final ServiceException e)
			{
				logger.warning("Can't send notification." + e.getMessage());
				botMessage.setBody("Something wrong. Can't send message.");
			}
			logger.info("Notification successfully sent.");
			chat.sendMessage(botMessage);
		}
		catch (final XMPPException e)
		{
			logger.warning("Can't send jabber message. " + e.getMessage());
		}
	}

}
